package com.fengchao.service;

import com.fengchao.config.Config;
import com.fengchao.dao.*;
import com.fengchao.model.*;
import com.fengchao.util.MailTools;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

@Service
@Transactional
public class PayService {
    @Autowired
    MailTools mailTools;
    @Autowired
    OdrOrderMapper odrOrderMapper;
    @Autowired
    CfiConcertCrowdfundingPayBackMapper cfiConcertCrowdfundingPayBackMapper;
    @Autowired
    OdrOrderItemsMapper odrOrderItemsMapper;
    @Autowired
    CfiConcertCrowdfundingSingalMapper cfiConcertCrowdfundingSingalMapper;
    @Autowired
    OdrOrderPaymentMapper odrOrderPaymentMapper;
    @Autowired
    PfmPerformanceTicketMapper odrTicketInfoMapper;


    private static final Logger logger = LoggerFactory.getLogger(PayService.class);

    /**
     * 支付成功 修改状态
     *
     * @param orderSn
     * @param payChannel
     * @return
     */
    @Transactional
    public Boolean paySucceed(String orderSn, Integer payChannel, String payAccount, String payTransactionNumber, BigDecimal totalFee) {
        //查询该订单号是否存在
        OdrOrder odrOrder = odrOrderMapper.findOdrOrderByOderSn(orderSn);
        if (odrOrder == null) {
            logger.error("支付成功，订单号不存在 orderSn：{}", orderSn);
            mailTools.SendMail("支付成功，订单号不存在", "orderSn" + orderSn, null);
            //创建订单支付记录
            createOrderPayment(null, orderSn, payChannel, totalFee, "SUCCESS", payAccount, payTransactionNumber);
            logger.info("创建订单支付记录 orderSn：{}", orderSn);
            return false;
        }
        if (totalFee.compareTo(odrOrder.getOrderPrice()) != 0) {
            logger.error("支付成功，支付金额与订单金额不同 orderSn：{},totalFee:{},orderPrice:{}", orderSn, totalFee, odrOrder.getOrderPrice());
            mailTools.SendMail("支付成功，支付金额与订单金额不同", "orderSn:" + orderSn + "otalFee:" + totalFee + "orderPrice:" + odrOrder.getOrderPrice(), null);
            //创建订单支付记录
            createOrderPayment(odrOrder.getId(), orderSn, payChannel, totalFee, "SUCCESS", payAccount, payTransactionNumber);
            logger.info("创建订单支付记录 orderSn：{}", orderSn);
            return false;
        }
        if (!"PAID".equals(odrOrder.getOrderStatus())) {//如果该订单还没有支付
            //修改该订单的支付状态为 已支付
            odrOrderMapper.update(payChannel, new Date(), "PAID", odrOrder.getId());
            logger.info("订单号修改状态 orderSn：{}", orderSn);
            //创建订单支付记录
            createOrderPayment(odrOrder.getId(), orderSn, payChannel, totalFee, "SUCCESS", payAccount, payTransactionNumber);
            logger.info("创建订单支付记录 orderSn：{}", orderSn);
        } else {
            logger.info("支付成功，订单号orderSn：{}已处理过", orderSn);
            return false;
        }
        return true;
    }

    /**
     * 支付失败 修改状态
     *
     * @param orderSn
     * @param payChannel
     * @return
     */
    @Transactional
    public Boolean payFailure(String orderSn, Integer payChannel, String payAccount, String payTransactionNumber) {
        //查询该订单号是否存在
        OdrOrder odrOrder = odrOrderMapper.findOdrOrderByOderSn(orderSn);
        if (odrOrder == null) {
            logger.error("支付失败，订单号不存在 orderSn：{}", orderSn);
            mailTools.SendMail("支付失败，订单号不存在", "orderSn:" + orderSn, null);
        }
        //创建订单支付记录
        createOrderPayment(odrOrder.getId(), orderSn, payChannel, odrOrder.getOrderPrice(), "SUCCESS", payAccount, payTransactionNumber);
        return true;
    }


    /**
     * 创建订单支付记录
     *
     * @param orderId
     * @param payChannel
     * @param orderPrice
     * @param payStatus
     * @return
     */
    @Transactional
    public Boolean createOrderPayment(Integer orderId, String orderSn, Integer payChannel, BigDecimal orderPrice, String payStatus, String payAccount, String payTransactionNumber) {
        OdrOrderPayment odrOrderPayment = new OdrOrderPayment();
        odrOrderPayment.setOrderId(orderId);
        odrOrderPayment.setOrderSn(orderSn);
        odrOrderPayment.setPayChannel(payChannel);
        odrOrderPayment.setPayAccount(payAccount);
        odrOrderPayment.setPayTransactionNumber(payTransactionNumber);
        odrOrderPayment.setPayMoney(orderPrice);
        odrOrderPayment.setPayStatus(payStatus);
        odrOrderPayment.setPayTime(new Date());
        odrOrderPayment.setCreateTime(new Date());
        Integer count = odrOrderPaymentMapper.insert(odrOrderPayment);
        return count > 0 ? true : false;
    }


    /**
     * 修改票实际购买人数
     *
     * @param ticketId
     * @param shares
     * @return
     */
    @Transactional
    public void updateTicket(Integer ticketId, Integer shares) {
        //累加回报实际购买数量
        PfmPerformanceTicket pfmPerformanceTicket = odrTicketInfoMapper.findById(ticketId);
        Integer ticketSoldSum = (pfmPerformanceTicket.getPfmTicketSoldSum() == null ? 0 : pfmPerformanceTicket.getPfmTicketSoldSum()) + shares;
        odrTicketInfoMapper.updateTicketSoldSum(pfmPerformanceTicket.getId(), ticketSoldSum);
        logger.info("增加票实际购买人数 ticketSoldSum：{}", ticketSoldSum);
    }

    /**
     * 修改回报实际购买人数
     *
     * @param payBackId
     * @param shares
     * @return
     */
    @Transactional
    public void updatePayback(Integer payBackId, Integer shares) {
        //累加回报实际购买数量
        CfiConcertCrowdfundingPayBack cfiConcertCrowdfundingPayBack = cfiConcertCrowdfundingPayBackMapper.findByPayBackId(payBackId);
        Integer payBackSoldSum = cfiConcertCrowdfundingPayBack.getPayBackSoldSum() + shares;
        cfiConcertCrowdfundingPayBackMapper.updatePayBackSoldSum(cfiConcertCrowdfundingPayBack.getId(), payBackSoldSum);
        logger.info("增加回报实际购买人数 payBackSoldSum：{}", payBackSoldSum);
    }

    /**
     * 修改众筹实际购买人数 钱
     *
     * @param crowdfundingId
     * @param Money
     * @param shares
     * @return
     */
    @Transactional
    public void updateCrowdfunding(Integer crowdfundingId, BigDecimal Money, Integer shares) {
        //累加众筹实际支持人数和金钱
        CfiConcertCrowdfundingSingal cfiConcertCrowdfundingSingal = cfiConcertCrowdfundingSingalMapper.findById(crowdfundingId);
        BigDecimal actualSumMoney = cfiConcertCrowdfundingSingal.getActualSumMoney().add(Money == null ? new BigDecimal(0) : Money);
        Integer actualSumShares = cfiConcertCrowdfundingSingal.getActualSumShares() + (shares == null ? 0 : shares);
        cfiConcertCrowdfundingSingalMapper.updateActualSumMoneyAndActualSumShares(actualSumMoney, actualSumShares, crowdfundingId);
        logger.info("修改众筹实际支持的人数和金额 actualSumMoney：{}，actualSumShares：{}", actualSumMoney, actualSumShares);
    }

    /**
     * 订单支付成功处理
     *
     * @return
     */
    public boolean orderSuccessDispose(String orderSn) {
        try {
            OdrOrder odrOrder = odrOrderMapper.findOdrOrderByOderSn(orderSn);
            if (odrOrder == null) {
                logger.error("该订单不存在，订单号为：{}", orderSn);
                mailTools.SendMail("支付宝回调地址订单不存在", "订单号为" + orderSn, null);
                return false;
            }
            List<OdrOrderItems> odrOrderItemsList = odrOrderItemsMapper.findByOrderId(odrOrder.getId());
            if (Config.CROWDFUNDING.equals(odrOrder.getBusinessType())) {//如果是众筹
                Integer count = 0;//众筹购买数量
                for (OdrOrderItems odrOrderItems : odrOrderItemsList) {
                    count = count + odrOrderItems.getGoodsTotalCount();
                    //更新众筹的回报实际购买
                    updatePayback(odrOrderItems.getGoodsId(), odrOrderItems.getGoodsTotalCount());
                }
                //更新众筹购买数量
                updateCrowdfunding(odrOrder.getBusinessId(), odrOrder.getOrderPrice().subtract(new BigDecimal(odrOrder.getPostage())), count);
            } else if (Config.PERFORMANCE.equals(odrOrder.getBusinessType())) {//如果是演唱会
                for (OdrOrderItems odrOrderItems : odrOrderItemsList) {
                    //更新演唱会的票的实际购买
                    updateTicket(odrOrderItems.getGoodsId(), odrOrderItems.getGoodsTotalCount());
                }
            } else {

            }
        } catch (Exception ex) {
            logger.error("支付成功累加实际购买数量异常 ex：{}", ex);
            mailTools.SendMail("支付成功累加实际购买数量异常", "系统异常", ex);
        }
        return true;
    }
}
